package ch.exm.storm.functional;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class ProxyIterator<T> implements InvocationHandler, Iterable<T> {
	
	private Collection<T> proxiedCollection;
	
	ProxyIterator(Collection<T> proxiedCollection) {
		this.proxiedCollection = proxiedCollection;
	}
	
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		if (method.getName().equals("iterator")) return iterator();
		return CollectionUtil.from(collectValues(method, args), method.getReturnType());
	}
	
	protected List<Object> collectValues(Method method, Object[] args) throws Throwable {
		List<Object> values = new ArrayList<Object>();
		for (T proxiedItem : proxiedCollection) {
			Object returnedObject = method.invoke(proxiedItem, args);
			values.add(returnedObject);
		}
		return values;
	}

	public Iterator<T> iterator() {
		return proxiedCollection.iterator();
	}
}
